package org.ix.dynamicapis.configure.utils;

import org.ix.dynamicapis.configure.models.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ExportToExcelUtils {

    public static void exportExcel(String sheetName, ApiModel apiModel, List<Map<String, Object>> list, String condition, OutputStream outputStream) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        exportExcel(workbook, sheetName, apiModel, list, condition);
        workbook.write(outputStream);
    }

    private static void exportExcel(Workbook workbook, String sheetName, ApiModel apiModel, List<Map<String, Object>> list, String condition) {

        Sheet sheet = workbook.createSheet(sheetName);
        CellStyle defaultHeaderCellStyle = getDefaultHeaderCellStyle(workbook);
        CellStyle defaultCellStyle = getDefaultCellStyle(workbook);

        Row row;
        Cell cell;
        int rowIndex = 0;
        int colIndex = 0;

        row = sheet.createRow(rowIndex++);
        // 设置header 高度
        row.setHeight((short) 512);

        if (apiModel.getApiExports() == null || apiModel.getApiExports().isEmpty()) return;

        List<ApiExportModel> apiExportModels = apiModel.getApiExports().stream()
                .filter(item -> condition.equals(item.getCondition()))
                .sorted(Comparator.comparingInt(ApiExportModel::getSort))
                .collect(Collectors.toList());

        for (ApiExportModel exportModel : apiExportModels) {
            // 设置每列宽度为20个字符，这个参数的单位是1/256个字符宽度
            int colWidth = 20;
            sheet.setColumnWidth(colIndex, colWidth * 256);
            cell = row.createCell(colIndex++);
            cell.setCellValue(exportModel.getExportName());
            cell.setCellStyle(defaultHeaderCellStyle);
        }

        // 新建所有行
        Row[] rows = new Row[list.size()];
        for (int i = 0; i < rows.length; i++) {
            Row rowItem = sheet.createRow(rowIndex++);
            rowItem.setHeight((short) 512);
            rows[i] = rowItem;
        }

        Map<String, Map<String, String>> apiFieldOptionsMap = apiModel.getApiFieldOptionsMap();
        colIndex = 0;
        for (ApiExportModel exportModel : apiExportModels) {
            Map<String, String> fieldEnumMap = apiFieldOptionsMap == null ? null : apiFieldOptionsMap.getOrDefault(exportModel.getName(), null);
            rowIndex = 0;
            if (fieldEnumMap == null || fieldEnumMap.isEmpty()) {
                for (Map<String, Object> item : list) {
                    cell = rows[rowIndex++].createCell(colIndex);
                    Object val = item.getOrDefault(exportModel.getName(), null);
                    String pattern = exportModel.getFormatter();
                    String value;
                    if (StringUtils.isBlank(pattern)) {
                        value = val == null ? "" : val + "";
                    } else {
                        if (val instanceof Date) {
                            value = getDateTime(val, pattern);
                        } else {
                            value = getVal(val, pattern);
                        }
                    }
                    cell.setCellValue(value);
                    cell.setCellStyle(defaultCellStyle);
                }
            } else {
                for (Map<String, Object> item : list) {
                    cell = rows[rowIndex++].createCell(colIndex);
                    Object val = item.getOrDefault(exportModel.getName(), null);
                    String value = fieldEnumMap.getOrDefault(val + "", val + "");
                    cell.setCellValue(value);
                    cell.setCellStyle(defaultCellStyle);
                }
            }
            colIndex++;
        }
    }

    /**
     * 获取表头单元格样式
     *
     * @param wb
     * @return
     */
    private static CellStyle getDefaultHeaderCellStyle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font titleFont = wb.createFont();
        titleFont.setFontHeightInPoints((short) 16);
        titleFont.setFontName("黑体");
        style.setFont(titleFont);
        return style;
    }

    /**
     * 获取默认单元格样式
     *
     * @param wb
     * @return
     */
    private static CellStyle getDefaultCellStyle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        style.setWrapText(true);
        return style;
    }

    private static String getDateTime(Object obj, String pattern) {
        if (obj == null) return "";
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(obj);
    }

    private static String getVal(Object obj, String pattern) {
        if (obj == null) return "";
        return String.format(pattern, obj);
    }
}
